/**
 * @file blankgamewidget.cpp
 * @brief 空白游戏页面组件实现文件
 *
 * 实现游戏认证完成后的过渡页面，提供平滑的用户体验。
 */

#include "../include/blankgamewidget.h"
#include "../include/config.h"
#include <QDebug>
#include <QApplication>
#include <QGraphicsDropShadowEffect>
#include <QEasingCurve>

/**
 * @brief BlankGameWidget构造函数
 * @param parent 父窗口指针
 */
BlankGameWidget::BlankGameWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_stackedWidget(nullptr)
    , m_loadingPage(nullptr)
    , m_welcomePage(nullptr)
    , m_loadingAnimationTimer(new QTimer(this))
    , m_fadeAnimation(nullptr)
    , m_opacityEffect(nullptr)
    , m_currentState(LoadingState)
    , m_loadingProgress(0)
    , m_animationFrame(0)
    , m_primaryColor("#4A90E2")
    , m_backgroundColor("#2C3E50")
    , m_textColor("#ECF0F1")
    , m_successColor("#27AE60")
{
    // === 设置窗口属性 ===
    setObjectName("BlankGameWidget");
    setMinimumSize(800, 600);
    
    // === 初始化UI ===
    setupUI();
    setupConnections();
    applyUnifiedTheme();
    
    // === 设置初始状态 ===
    setPageState(LoadingState);
    
    qDebug() << "BlankGameWidget: 组件初始化完成";
}

/**
 * @brief BlankGameWidget析构函数
 */
BlankGameWidget::~BlankGameWidget()
{
    // 停止动画
    if (m_loadingAnimationTimer) {
        m_loadingAnimationTimer->stop();
    }
    if (m_fadeAnimation) {
        m_fadeAnimation->stop();
    }
    
    qDebug() << "BlankGameWidget: 组件销毁";
}

/**
 * @brief 设置UI界面
 */
void BlankGameWidget::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    
    // === 创建堆叠窗口 ===
    m_stackedWidget = new QStackedWidget(this);
    m_stackedWidget->setObjectName("blankGameStackedWidget");
    
    // === 设置页面 ===
    setupLoadingPage();
    setupWelcomePage();
    
    m_mainLayout->addWidget(m_stackedWidget);
}

/**
 * @brief 设置加载页面
 */
void BlankGameWidget::setupLoadingPage()
{
    m_loadingPage = new QWidget();
    m_loadingPage->setObjectName("loadingPage");
    
    QVBoxLayout *loadingLayout = new QVBoxLayout(m_loadingPage);
    loadingLayout->setAlignment(Qt::AlignCenter);
    loadingLayout->setSpacing(30);
    loadingLayout->setContentsMargins(50, 50, 50, 50);
    
    // === 加载图标 ===
    m_loadingIconLabel = new QLabel("🎮");
    m_loadingIconLabel->setObjectName("loadingIcon");
    m_loadingIconLabel->setAlignment(Qt::AlignCenter);
    m_loadingIconLabel->setStyleSheet("font-size: 72px;");
    loadingLayout->addWidget(m_loadingIconLabel);
    
    // === 加载标题 ===
    m_loadingTitleLabel = new QLabel("正在加载游戏...");
    m_loadingTitleLabel->setObjectName("loadingTitle");
    m_loadingTitleLabel->setAlignment(Qt::AlignCenter);
    loadingLayout->addWidget(m_loadingTitleLabel);
    
    // === 进度条 ===
    m_loadingProgressBar = new QProgressBar();
    m_loadingProgressBar->setObjectName("loadingProgressBar");
    m_loadingProgressBar->setRange(0, 100);
    m_loadingProgressBar->setValue(0);
    m_loadingProgressBar->setTextVisible(true);
    m_loadingProgressBar->setMaximumWidth(400);
    loadingLayout->addWidget(m_loadingProgressBar, 0, Qt::AlignCenter);
    
    // === 加载消息 ===
    m_loadingMessageLabel = new QLabel("正在初始化游戏组件...");
    m_loadingMessageLabel->setObjectName("loadingMessage");
    m_loadingMessageLabel->setAlignment(Qt::AlignCenter);
    loadingLayout->addWidget(m_loadingMessageLabel);
    
    m_stackedWidget->addWidget(m_loadingPage);
}

/**
 * @brief 设置欢迎页面
 */
void BlankGameWidget::setupWelcomePage()
{
    m_welcomePage = new QWidget();
    m_welcomePage->setObjectName("welcomePage");
    
    QVBoxLayout *welcomeLayout = new QVBoxLayout(m_welcomePage);
    welcomeLayout->setAlignment(Qt::AlignCenter);
    welcomeLayout->setSpacing(20);
    welcomeLayout->setContentsMargins(50, 50, 50, 50);
    
    // === 欢迎标题 ===
    m_welcomeTitleLabel = new QLabel("🎉 欢迎进入游戏！");
    m_welcomeTitleLabel->setObjectName("welcomeTitle");
    m_welcomeTitleLabel->setAlignment(Qt::AlignCenter);
    welcomeLayout->addWidget(m_welcomeTitleLabel);
    
    // === 游戏信息 ===
    m_gameInfoLabel = new QLabel();
    m_gameInfoLabel->setObjectName("gameInfo");
    m_gameInfoLabel->setAlignment(Qt::AlignCenter);
    m_gameInfoLabel->setWordWrap(true);
    welcomeLayout->addWidget(m_gameInfoLabel);
    
    // === 游戏描述 ===
    m_gameDescriptionEdit = new QTextEdit();
    m_gameDescriptionEdit->setObjectName("gameDescription");
    m_gameDescriptionEdit->setReadOnly(true);
    m_gameDescriptionEdit->setMaximumHeight(200);
    m_gameDescriptionEdit->setMaximumWidth(600);
    welcomeLayout->addWidget(m_gameDescriptionEdit, 0, Qt::AlignCenter);
    
    // === 按钮布局 ===
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(20);
    
    m_backButton = new QPushButton("⬅️ 返回主页");
    m_backButton->setObjectName("backButton");
    m_backButton->setMinimumSize(120, 40);
    buttonLayout->addWidget(m_backButton);
    
    m_readyButton = new QPushButton("🚀 开始游戏");
    m_readyButton->setObjectName("readyButton");
    m_readyButton->setMinimumSize(120, 40);
    buttonLayout->addWidget(m_readyButton);
    
    welcomeLayout->addLayout(buttonLayout);
    
    m_stackedWidget->addWidget(m_welcomePage);
}

/**
 * @brief 设置连接
 */
void BlankGameWidget::setupConnections()
{
    // 加载动画定时器
    connect(m_loadingAnimationTimer, &QTimer::timeout,
            this, &BlankGameWidget::onLoadingAnimation);
    
    // 按钮连接
    if (m_backButton) {
        connect(m_backButton, &QPushButton::clicked,
                this, &BlankGameWidget::onBackButtonClicked);
    }
    
    if (m_readyButton) {
        connect(m_readyButton, &QPushButton::clicked,
                this, &BlankGameWidget::pageReady);
    }
}

/**
 * @brief 显示游戏页面
 * @param gameType 游戏类型
 * @param serverName 服务器名称
 * @param playerName 玩家名称
 */
void BlankGameWidget::showGamePage(const QString &gameType, const QString &serverName, const QString &playerName)
{
    m_gameType = gameType;
    m_serverName = serverName;
    m_playerName = playerName;
    
    // 更新UI显示
    QString gameIcon = getGameTypeIcon(gameType);
    m_loadingIconLabel->setText(gameIcon);
    m_loadingTitleLabel->setText(QString("正在加载%1游戏...").arg(gameType.toUpper()));
    
    // 更新游戏信息
    QString gameInfo = QString("%1 <b>%2</b><br/>服务器: %3<br/>玩家: %4")
                      .arg(gameIcon)
                      .arg(gameType.toUpper())
                      .arg(serverName)
                      .arg(playerName);
    m_gameInfoLabel->setText(gameInfo);
    
    // 更新游戏描述
    m_gameDescriptionEdit->setHtml(getGameDescription(gameType));
    
    // 显示窗口并开始加载
    show();
    raise();
    activateWindow();
    
    setPageState(LoadingState);
    startLoadingAnimation();
    
    qDebug() << "BlankGameWidget: 显示游戏页面 -" << gameType << serverName << playerName;
}

/**
 * @brief 隐藏游戏页面
 */
void BlankGameWidget::hideGamePage()
{
    stopLoadingAnimation();
    hide();
    
    qDebug() << "BlankGameWidget: 隐藏游戏页面";
}

/**
 * @brief 设置页面状态
 * @param state 页面状态
 */
void BlankGameWidget::setPageState(PageState state)
{
    if (m_currentState == state) {
        return;
    }
    
    m_currentState = state;
    
    switch (state) {
    case LoadingState:
        m_stackedWidget->setCurrentWidget(m_loadingPage);
        startLoadingAnimation();
        break;
        
    case WelcomeState:
        m_stackedWidget->setCurrentWidget(m_welcomePage);
        stopLoadingAnimation();
        break;
        
    case ReadyState:
        stopLoadingAnimation();
        emit pageReady();
        break;
    }
    
    qDebug() << "BlankGameWidget: 页面状态切换到" << static_cast<int>(state);
}

/**
 * @brief 更新加载进度
 * @param progress 进度值 (0-100)
 * @param message 进度消息
 */
void BlankGameWidget::updateLoadingProgress(int progress, const QString &message)
{
    m_loadingProgress = qBound(0, progress, 100);
    m_loadingProgressBar->setValue(m_loadingProgress);
    
    if (!message.isEmpty()) {
        m_loadingMessageLabel->setText(message);
    }
    
    // 当进度达到100%时，切换到欢迎页面
    if (m_loadingProgress >= 100) {
        QTimer::singleShot(1000, this, [this]() {
            setPageState(WelcomeState);
        });
    }
    
    qDebug() << "BlankGameWidget: 更新进度" << progress << "%" << message;
}

/**
 * @brief 应用统一主题
 */
void BlankGameWidget::applyUnifiedTheme()
{
    QString styleSheet = QString(R"(
        BlankGameWidget {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 %1, stop:0.5 #34495E, stop:1 #2C3E50);
            color: %2;
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
        }
        
        QWidget#loadingPage, QWidget#welcomePage {
            background: transparent;
        }
        
        QLabel#loadingTitle, QLabel#welcomeTitle {
            font-size: 24px;
            font-weight: bold;
            color: %2;
            margin: 10px;
        }
        
        QLabel#loadingMessage, QLabel#gameInfo {
            font-size: 14px;
            color: #BDC3C7;
            margin: 5px;
        }
        
        QProgressBar#loadingProgressBar {
            border: 2px solid %1;
            border-radius: 8px;
            background-color: #34495E;
            text-align: center;
            font-weight: bold;
            color: %2;
            min-height: 25px;
        }
        
        QProgressBar#loadingProgressBar::chunk {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 %3, stop:1 #5DADE2);
            border-radius: 6px;
        }
        
        QTextEdit#gameDescription {
            background-color: rgba(52, 73, 94, 0.8);
            border: 2px solid %1;
            border-radius: 8px;
            color: %2;
            font-size: 13px;
            padding: 10px;
        }
        
        QPushButton#backButton, QPushButton#readyButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %1, stop:1 #2980B9);
            border: 2px solid %1;
            border-radius: 8px;
            color: %2;
            font-size: 14px;
            font-weight: bold;
            padding: 8px 16px;
            min-width: 100px;
        }
        
        QPushButton#backButton:hover, QPushButton#readyButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #5DADE2, stop:1 %1);
            border-color: #5DADE2;
        }
        
        QPushButton#backButton:pressed, QPushButton#readyButton:pressed {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #2980B9, stop:1 #1F4E79);
        }
        
        QPushButton#readyButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %4, stop:1 #229954);
        }
        
        QPushButton#readyButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #58D68D, stop:1 %4);
        }
    )").arg(m_primaryColor, m_textColor, m_primaryColor, m_successColor);
    
    setStyleSheet(styleSheet);
}

/**
 * @brief 开始加载动画
 */
void BlankGameWidget::startLoadingAnimation()
{
    if (!m_loadingAnimationTimer->isActive()) {
        m_animationFrame = 0;
        m_loadingAnimationTimer->start(200); // 200ms间隔
    }
}

/**
 * @brief 停止加载动画
 */
void BlankGameWidget::stopLoadingAnimation()
{
    if (m_loadingAnimationTimer->isActive()) {
        m_loadingAnimationTimer->stop();
    }
}

/**
 * @brief 加载动画定时器槽
 */
void BlankGameWidget::onLoadingAnimation()
{
    // 旋转加载图标
    QStringList loadingIcons = {"🎮", "🎯", "🎲", "🕹️"};
    int iconIndex = m_animationFrame % loadingIcons.size();
    m_loadingIconLabel->setText(loadingIcons[iconIndex]);
    
    // 更新进度（模拟加载过程）
    if (m_loadingProgress < 100) {
        int increment = 1 + (m_animationFrame % 3); // 1-3的随机增量
        updateLoadingProgress(m_loadingProgress + increment, "");
    }
    
    m_animationFrame++;
}

/**
 * @brief 返回按钮点击槽
 */
void BlankGameWidget::onBackButtonClicked()
{
    qDebug() << "BlankGameWidget: 用户点击返回主页";
    emit backToMainPage();
}

/**
 * @brief 获取游戏类型图标
 * @param gameType 游戏类型
 * @return 图标文本
 */
QString BlankGameWidget::getGameTypeIcon(const QString &gameType) const
{
    QString type = gameType.toLower();
    if (type == "snake") {
        return "🐍";
    } else if (type == "tetris") {
        return "🧩";
    } else if (type == "puzzle") {
        return "🧠";
    } else {
        return "🎮";
    }
}

/**
 * @brief 获取游戏描述
 * @param gameType 游戏类型
 * @return 游戏描述文本
 */
QString BlankGameWidget::getGameDescription(const QString &gameType) const
{
    QString type = gameType.toLower();
    
    if (type == "snake") {
        return QString(
            "<h3>🐍 Snake Game</h3>"
            "<p>经典的贪吃蛇游戏，支持多人在线对战！</p>"
            "<ul>"
            "<li>🕹️ 实时多人对战</li>"
            "<li>💬 游戏内聊天系统</li>"
            "<li>🏆 全球排行榜</li>"
            "<li>🎯 多种游戏模式</li>"
            "<li>⚡ WebSocket低延迟连接</li>"
            "</ul>"
            "<p><b>操作说明：</b>使用方向键或WASD控制蛇的移动方向</p>"
        );
    } else if (type == "tetris") {
        return QString(
            "<h3>🧩 Tetris Game</h3>"
            "<p>经典俄罗斯方块，挑战你的空间思维！</p>"
            "<ul>"
            "<li>🎮 经典玩法</li>"
            "<li>⚡ 快节奏挑战</li>"
            "<li>🏆 高分排行榜</li>"
            "<li>🎨 精美界面</li>"
            "</ul>"
        );
    } else if (type == "puzzle") {
        return QString(
            "<h3>🧠 Puzzle Game</h3>"
            "<p>益智解谜游戏，锻炼你的逻辑思维！</p>"
            "<ul>"
            "<li>🧩 多种谜题类型</li>"
            "<li>🎯 难度逐步提升</li>"
            "<li>💡 提示系统</li>"
            "<li>📊 详细统计</li>"
            "</ul>"
        );
    } else {
        return QString(
            "<h3>🎮 Game</h3>"
            "<p>准备好开始游戏了吗？</p>"
            "<p>享受愉快的游戏时光！</p>"
        );
    }
}

